<?php

namespace Apps\AppApi\Method\Note;

use Apps\AppApi\Method\BaseMethod;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\Inorout;
use Phalcon\Mvc\Model;


/**
 * 添加记事本收支分类
 * @author      545
 * @date        2016年3月4日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class AddInorout extends BaseMethod
{
    /**
     * @var \Apps\Common\Models\AddInorout
     */
    private $success = 0;
    private $id = 0;

    public function run()
    {
        //验证是否登录
        if(false == $this->verifyUserAuth()){
            return false;
        }
        
    	$inorout_title = $this->getDataItem('title');
    	$childtitle = $this->getDataItem('childtitle');
    	$parentid = $this->getDataItem('parentid');
    	$type = $this->getDataItem('type',1);
    	if (empty($inorout_title)&&empty($childtitle)){
    	    return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR,'标题为空');
    	}
    	
    	if (!in_array($type,[1,2])){
    	    return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR,'所属不明确');
    	}
    	
    	$info = Inorout::findFirst("inorout_title = '{$inorout_title}' AND user_id = {$this->getUserAuth()->userId}");
    	
    	if ($info){//验证分类是否存在
    	    return $this->setResult(['success' => $this->success,'message'=>'数据已存在']);
    	}
    	
    	$data['inorout_title'] = $inorout_title;
    	$data['createtime'] = date("Y-m-d H:i:s", time());
    	$data['user_id'] = $this->getUserAuth()->userId;
    	$data['type'] = $type;
    	if ($parentid>0){//如果上传了父类id
    	    $info = Inorout::findFirst("inorout_id = {$parentid}");
    	    if ($info->parent_id>0){//验证父类是否是第一级分类
    	        return $this->errorLog(ResultStatus::DATABASE_ERROR,"只能添加二级分类");
    	    } 
    	    $data['parent_id'] = $parentid;
    	}
    	
    	$inorout = new Inorout();
    	
    	if ($inorout->save($data)){//保存分类
    	    $this->id = $inorout->inorout_id;
    	    $this->success = 1;
    	    if (!empty($childtitle)&&empty($parentid)){//检查是否上传子类,并且不是添加二级分类
    	        
    	        $temp['inorout_title'] = $childtitle;
            	$temp['createtime'] = date("Y-m-d H:i:s", time());
            	$temp['user_id'] = $this->getUserAuth()->userId;
            	$temp['parent_id'] = $this->id;
            	//添加子类
            	$inorout = new Inorout();
            	$inorout ->save($temp);
    	    }
    	    
    	    $this->setResult([
    	        'id' => $this->id,
    	        'success' => $this->success
    	    ]);
    	    
    	}
    	else {
    	    $this->errorLog(ResultStatus::DATABASE_ERROR,"写入失败");
    	}
        
        
    }

}